package com.gitee.huxing.course.netty.client;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;

import java.net.URI;
import java.nio.charset.StandardCharsets;

import static io.netty.handler.codec.http.HttpHeaderNames.HOST;
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpMethod.POST;

/**
 * @Description: 创建一个http的请求报文
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.netty.client
 * @ClassName: HttpCreateBuilder
 * @Author: huxing
 * @DateTime: 2021-08-19 下午2:10
 */
public class HttpCreateBuilder {

    /**
     * @Description: 创建Http请求报文
     * @Author: huxing
     * @param body
     * @param url
     * @return org.springframework.http.HttpRequest
     * @Date: 2021/8/19 下午2:11
     **/
    public HttpRequest createGetRequest(String body, String url) throws Exception{
        return this.createRequest(body, new URI(url), GET);
    }

    /**
     * @Description: 创建Http请求报文
     * @Author: huxing
     * @param body
     * @param url
     * @return org.springframework.http.HttpRequest
     * @Date: 2021/8/19 下午2:11
     **/
    public HttpRequest createPostRequest(String body, String url) throws Exception{
        return this.createRequest(body, new URI(url), POST);
    }

    /**
     * @Description: 报文内容处理
     * @Author: huxing
     * @param
     * @return io.netty.handler.codec.http.HttpRequest
     * @Date: 2021/8/19 下午2:22
     **/
    private FullHttpRequest createRequest(String body, URI uri, HttpMethod method){
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, method,
                uri.toASCIIString(), Unpooled.wrappedBuffer(body.getBytes(StandardCharsets.UTF_8)));
        request.headers().set(CONNECTION, KEEP_ALIVE);
        request.headers().set("accept-type", StandardCharsets.UTF_8);
        request.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
        request.headers().set(CONTENT_LENGTH, request.content().readableBytes());
        return request;
    }
}
